package 面向对象.实验9;

/**
 * @author IT_Jay
 * @date 2021/12/2 11:30
 */
//演示生产者-消费者问题的主程序

public class Test03 {
    public static void main(String[] args) {
        Buffer buffer = new Buffer();
        new Producer(buffer,101).start();
        new Consumer(buffer,200).start();
        new Consumer(buffer,201).start();

    }
}
//生产者线程
class Producer extends Thread
{
    /*补充完整 */
    private Buffer buffer;
    private int number;

    public Producer(Buffer buffer, int number) {
        super();
        this.buffer = buffer;
        this.number = number;
    }
    @Override
    public void run(){
        super.run();
        for (int i=0;i<6;){
            buffer.put(i);
            System.out.println("生产者#"+number+"生产"+(i++));
            try {
                Thread.sleep((int)(Math.random()*2000));
            }catch (InterruptedException e){

            }
        }
    }
}

//消费者线程
class Consumer extends Thread
{
    private Buffer buffer;
    private int number;


    public Consumer(Buffer buffer,int number)
    {
        super();
        this.buffer = buffer;
        this.number = number;
    }
    @Override
    public void run()
    {
        super.run();
        for(int i=0;i<3;i++)
        {
            int v=buffer.get();

                    System.out.println("消费者#"+number+"消费"+v);

        }
    }
}
//有界缓冲区类Buffer.java文件内容如下:

//生产者与消费者共享的缓冲区,必须实现读,写的同步
class Buffer
{
    private int contents;
    private boolean available=false;

    public synchronized int get()
    {
        while(!available)
        {
            try{
                this.wait();
            } catch(InterruptedException exc){ exc.printStackTrace(); }
        }
        int value=contents;
        //消费者取出内容,改变存取控制available
        available=false;
        System.out.println("取出"+contents);
        this.notifyAll();       //解除wait状态
        return value;
    }
    public synchronized void put(int value)
    {
        while(available)
        {
            try{
                this.wait();
            }catch(InterruptedException exc){ exc.printStackTrace(); }
        }
        contents=value;
        //生产者放入内容,改变存取控制available
        available=true;
        System.out.println("放入"+contents);
        this.notifyAll();
    }
}

//演示生产者-消费者问题的主程序
//public class ProducerConsumerProblem
//{
//    public static void main(String[] args)
//    {
//        Buffer buffer=new Buffer();
//        new Producer(buffer,101).start();
//        new Consumer(buffer,200).start();
//        new Consumer(buffer,201).start();
//
//    }
//}
